package com.sx.code.service.impl;

import com.netflix.discovery.converters.Auto;
import com.sx.code.dao.AuthCodeRepository;
import com.sx.code.entity.AuthCode;
import com.sx.code.service.CodeService;
import com.sx.code.service.EmailFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author shengx
 * @date 2020/5/13 23:21
 */
@Service
public class CodeServiceImpl implements CodeService {
    @Autowired
    private EmailFeignClient emailFeignClient;
    @Autowired
    private AuthCodeRepository authCodeRepository;
    private static int TEN_MIN = 10 * 60 * 1000;
    private static String STR = "0123456789";
    private static int CODE_LENGTH = 6;

    @Override
    @Transactional
    public Boolean createCode(String email) {
        String code = genCode(CODE_LENGTH);
        Long curr = System.currentTimeMillis();
        Long expire = curr + TEN_MIN;
        AuthCode authCode = new AuthCode();
        authCode.setCode(code);
        authCode.setCreatetime(curr);
        authCode.setExpiretime(expire);
        authCode.setEmail(email);
        // 验证码入库
        authCodeRepository.save(authCode);
        // feign远程调用邮件服务发送code
        Boolean success = emailFeignClient.email(email, code);
        return success;
    }

    @Override
    public Integer checkCode(String email, String code) {
        List<AuthCode> authCodes = authCodeRepository.findAuthCodesByEmail(email);
        long curr = System.currentTimeMillis();
        for (AuthCode authCode : authCodes) {
            // code 有效且正确
            if (authCode.getCode().equals(code) && (authCode.getExpiretime() >= curr)) {
                return 0;
            } else if (authCode.getCode().equals(code) && (authCode.getExpiretime() < curr)) {
                return 2;
            }
        }
        return 1;
    }


    private String genCode(int length) {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(9);
            sb.append(STR.charAt(number));
        }
        return sb.toString();
    }
}
